package com.example.gyj.service;

import com.example.gyj.dao.UserDao;
import com.example.gyj.entity.User;
import com.example.gyj.exception.GlobalException;
import com.example.gyj.redis.UserKey;
import com.example.gyj.result.CodeMsg;
import com.example.gyj.util.Md5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Gao
 * @date 2018/10/21
 */
@Service
public class UserService {

    public static final String COOKIE_NAME_TOKEN = "token";

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private LoginService loginService;

    /**
     * 根据用户Id取User对象
     * @param id
     */
    public User getUserById(long id) {
        //取缓存
        User user = redisService.get(UserKey.getById, "" + id, User.class);
        if (user != null) {
            return user;
        }
        //取数据库
        user = userDao.getUserById(id);
        if (user != null) {
            redisService.set(UserKey.getById, "" + id, user);
        }

        return user;
    }

    /**
     * 更新密码
     * @param token
     * @param id
     * @param fromPass
     * @return
     */
    public boolean updatePassword(String token, long id, String fromPass) {
        User user = this.getUserById(id);
        if (user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        //更新数据库
        User toBeUpdateUser = new User();
        toBeUpdateUser.setId(id);
        toBeUpdateUser.setPassword(Md5Util.fromPassToDBPass(fromPass, user.getSalt()));
        userDao.update(toBeUpdateUser);
        //处理缓存
        redisService.delete(UserKey.getById, "" + id);
        user.setPassword(toBeUpdateUser.getPassword());
        redisService.set(UserKey.token, token, user);
        return true;
    }

    /**
     * 根据token得到user对象
     * @param response
     * @param token
     */
    public User getUserByToken(HttpServletResponse response, String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        User user = redisService.get(UserKey.token, token, User.class);
        //延长有效期
        if (user != null) {
            loginService.addCookie(response, token, user);
        }
        return user;
    }
}
